<template>
  <b-container fluid>
    <b-row>
      <b-col />
      <!-- 侧边栏 -->
      <b-col class="side" sm="2">
        <b-row style="border-bottom: 1px solid black; font-size: 120%">
          <b-col><span>在线人数:</span></b-col>
          <b-col style="text-align: right">{{ users.length }}</b-col>
        </b-row>
        <b-row v-for="u in users" :key="u.username">
          <b-col class="userList">{{ u.username }}</b-col>
        </b-row>
      </b-col>

      <!-- 主区域 -->
      <b-col class="main" sm="9">
        <!-- 信息显示区 -->
        <!--  -->
        <b-row style="height: 550px; overflow: hidden; overflow-y: scroll">
          <b-container v-html="content" class="message"> </b-container>
        </b-row>

        <!-- 消息编辑区 -->
        <b-row
          style="
            height: 30px;
            border-bottom: 1px solid black;
            border-top: 1px solid black;
          "
        >
          <b-col>
            <span>表情</span>
          </b-col>
          <b-col sm="4" style="text-align: right">
            <b-link @click="send" class="linkStyle">发送</b-link>
          </b-col>
        </b-row>
        <b-row>
          <textarea v-model="text" class="edit"/>
        </b-row>
      </b-col>

      <b-col />
    </b-row>
  </b-container>
</template>

<script>
// import request from '@/utils/request'
import axios from "axios";
// import moment from "moment";
let socket;
export default {
  name: "ChatMain",
  data() {
    return {
      user: [],
      isCollapse: false,
      users: {},
      chatUser: "",
      text: "",
      messages: [],
      content: "",
      //登录状态
      id: "",
      isLogin: false,
    };
  },
  created() {
    this.iflogin();
  },
  methods: {
    send() {
      if (!this.text) {
        this.$message({ type: "warning", message: "请输入内容" });
      } else {
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {
            from: this.user.username,
            to: this.chatUser,
            text: this.text,
          };
          socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
          this.messages.push({ user: this.user.username, text: this.text });
          // 构建消息内容，本人消息
          this.createContent(null, this.user.username, this.text);
          this.text = "";
        }
      }
    },
    createContent(remoteUser, nowUser, text, url) {
      // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html;
      // 当前用户消息
      if (nowUser) {
        // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html =
          "<div class='row' style='height: 60px;margin-bottom:1%'><div class='col-sm-1'><img style='max-width: 60px;' class='img-thumbnail rounded-circle mx-auto d-block' src='" +
          this.user.avaterUrl +
          "'/></div><div class='col'><div class='row'><span>" +
          nowUser +
          "" +
          "</span></div><div class='row'><div style=' border-radius: 10px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 20px rgba(0, 0, 0, 0.04);background-color: lawngreen;width: auto;'><p>" +
          text +
          "</p></div></div></div></div>";
      } else if (remoteUser) {
        // remoteUser表示远程用户聊天消息，蓝色的气泡
        html =
          "<div class='row' style='height: 60px;margin-bottom:1%'><div class='col-sm-1'><img style='max-width: 60px;' class='img-thumbnail rounded-circle mx-auto d-block' src='" +
          url +
          "'/></div><div class='col'><div class='row'><span>" +
          remoteUser +
          "" +
          "</span></div><div class='row'><div style=' border-radius: 10px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 20px rgba(0, 0, 0, 0.04);background-color: rgb(255, 255, 255);width: auto;'><p>" +
          text +
          "</p></div></div></div></div>";
      }
      console.log(html);
      this.content += html;
    },
    //跳转登录
    toLogin() {
      this.$router.push({
        path: "/login",
        params: {
          title: "登录",
        },
      });
    },
    //查询登录状态
    iflogin() {
      axios
        .get("http://localhost:8081/user/iflogin", {
          params: {
            token: localStorage.getItem("token"),
          },
        })
        .then((res) => {
          if (res.data == "") {
            this.isLogin = false;
            localStorage.removeItem("token");
            console.log("没有登录");
            this.toLogin();
          } else {
            console.log("已登录-->", res.data);
            this.isLogin = true;
            this.id = res.data;
            this.getUserData();
          }
        })
        .catch(() => {
          this.toLogin();
        });
    },
    //获取用户数据
    getUserData() {
      axios
        .get("http://localhost:8081/user/serachUser", {
          params: {
            id: this.id,
          },
        })
        .then((res) => {
          this.user = res.data;
          this.init();
          // console.log("获取到的用户数据-->", this.user);
        })
        .catch((err) => {
          console.error(err);
        });
    },
    init() {
      let username = this.user.nickName;
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8081/kunserver/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          // console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data); // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) {
            // 获取在线人员信息
            _this.users = data.users;
            // console.log("在线人员:",_this.users)
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            _this.messages.push(data);
            // 构建消息内容
            _this.createContent(data.from, null, data.text, data.url);
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
  },
};
</script>

<style scoped lang="css">
.main {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 20px rgba(0, 0, 0, 0.04);
  max-width: 900px;
  margin: 1%;
  height: 750px;
  margin-left: 0%;
  overflow: hidden;
}
.side {
  max-width: 300px;
  margin: 1%;
  height: 750px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 20px rgba(0, 0, 0, 0.04);
}
.message {
  max-height: 550px;
}
.edit {
  height: 170px;
  outline: none;
  border: none;
  resize: none;
  flex-wrap: wrap;
  font-size: 18px;
}
.userList {
  color: lightcoral;
  font-size: 20px;
}
</style>